package com.flow.framework.core.validation.validator;

import com.flow.framework.common.exception.ParamCheckedException;
import com.flow.framework.core.validation.annotation.MaxCustomization;
import com.flow.framework.core.validation.validator.base.BaseValidator;

import javax.validation.ConstraintValidatorContext;

/**
 * Max 校验器
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/22
 */
public class MaxValidator extends BaseValidator<MaxCustomization, Number> {
    private MaxCustomization maxCustomization;

    private String errorMsg;

    @Override
    public void initialize(MaxCustomization maxCustomization) {
        this.maxCustomization = maxCustomization;
        this.errorMsg = "value greater than" + maxCustomization.value();
    }

    @Override
    public boolean isValid(Number value, ConstraintValidatorContext context) {
        if (null == maxCustomization) {
            return true;
        }
        if (maxCustomization.containsEquals()) {
            if (value.longValue() > maxCustomization.value()) {
                super.logError(context, value, errorMsg);
                throw new ParamCheckedException(maxCustomization.errorCode());
            }
        } else {
            if (value.longValue() >= maxCustomization.value()) {
                super.logError(context, value, errorMsg);
                throw new ParamCheckedException(maxCustomization.errorCode());
            }
        }
        return true;
    }
}
